<!-- 确认订单 点击立即购买或者去结算跳转的页面 -->
<template>
	<!-- 收货地址部分  点击收货地址跳转收货地址界面-->
	<view class="pay-address" v-for="(item,index) in address" :key="index" @click="choose">
		<!-- 左边定位图标 -->
		<view class="pay-address-left">
			<image src="/static/images/order-locating.svg" mode="aspectFit"></image>
		</view>
		<!-- 右边收货地址个人信息 -->
		<view class="pay-address-name">
			<view>
				<text>{{item.name}}</text>
				<text>{{item.telephone}}</text>
			</view>
			<text>{{item.region + item.address}}</text>
		</view>
		<!-- 右边箭头 -->
		<view class="pay-address-right">
			<image src="/static/images/right-arrow.svg" mode="aspectFit"></image>
		</view>
	</view>

	<!-- 商品详情部分 -->
	<view class="pay-goods" v-for="(item,index) in order" :key="index">
		<!-- 商品图片 -->
		<view>
			<image :src="item.goods_image" mode="aspectFill"></image>
		</view>
		
		<!-- 商品标题部分 -->
		<view>
			<text class="pay-goods-title">{{item.goods_title}}</text>
			<!-- 如果商品有规格就展示规格 -->
			<text class="pay-goods-specs" v-if="item.specs.length > 0" v-for="(item2,index2) in item.specs" :key="index2">{{item2.att_val}}</text>

			<view class="pay-goods-price">
				<text>¥{{item.goods_price}}</text>
				<!-- 购物车多个购买不能操作数量加减 -->
				<text v-if="type != 'direct'">x{{item.buy_amount}}</text>
				<!-- 商品详情页直接下单可以操作数量 -->
				<view v-else>
					<image src="/static/images/sub.png" mode="aspectFit" @click="sub" :class="[item.buy_amount == 1 ? 'prevent_style' : '']"></image>
					<text>{{item.buy_amount}}</text>
					<image src="/static/images/add.png" mode="aspectFit" @click="add"></image>
				</view>
			</view>
		</view>
	</view>

	<!-- 底部提交订单按钮 -->
	<view style="300rpx"></view> <!-- 防止底部按钮将商品覆盖-->
	<view class="commit-order">
		<view>¥{{total_price}}</view>
		<view @click="submit">提交订单</view>
	</view>

	<!-- 支付弹窗 -->
	<page-container :show="show" round="true" @clickoverlay="cancelPay">
		<view class="customStyle">
			<view class="container-guan">
				<image src="/static/images/close.svg" mode="widthFix" @click="cancelPay"></image>
			</view>
			<view class="container-price">
				<text>零食商城平台</text>
				<text>¥ {{total_price}}</text>
			</view>
			<view class="Payment-Methods">
				<text>支付方式</text>
				<text>零钱通</text>
			</view>
			<view class="Confirm-payment">
				<button type="primary" :loading="loading" @click="confirmPay">确认支付</button>
			</view>
		</view>
	</page-container>

</template>

<script setup>
	import { onMounted, reactive, toRefs, watch, onBeforeUnmount } from 'vue'
	import { receive_box } from "@/public/package-js/passValue.js"
	import { onLoad } from '@dcloudio/uni-app'
	import { merchantNo, orderNo } from "../../public/package-js/orderNumber.js"
	import {Pay} from "@/public/package-js/pay.js"
	import { FeedBack } from "@/public/package-js/feedBack.js"
	import moment from 'moment'
	moment.locale('zh-cn');


	const data = reactive({
		address: [], // 存放选择的地址（不选择就是默认地址）
		order: [], // 传递的订单商品数据
		type: '', // 传递的类型是 加入购物车还是 立即购买
		total_price: 0, // 所有结算订单总价
		show: false, // 控制支付弹窗
		loading: false, // 控制支付按钮是否带 loading图标
		merchant_no: '',  // 商户订单号
	})
	const { address, order, type, total_price, show, loading } = toRefs(data)

	// 1、进入界面展示默认地址
	const db = wx.cloud.database()
	onMounted(async () => {
		const res = await db.collection('receiver_address').where({ isChecked: true }).get()
		data.address = res.data
	})

	// 2、点击地址，跳转收货地址界面选择新的地址
	function choose() {
		uni.navigateTo({
			url: '/pages/receiver-address/receiver-address'
		})
	}
	// 3、将收货地址界面选择的地址进行赋值
	watch(() => receive_box.selectAddress, (newVal, oldVal) => {
		console.log("newVal", newVal);
		data.address = [newVal] // 赋值成数组
	})

	// 4、接收上个页面传来的值
	onLoad((event) => {
		const res = JSON.parse(event.order)
		console.log("event", event)
		data.order = res
		data.type = event.type
		// 遍历计算待支付的价格
		let sum = 0
		data.order.forEach((item => sum += item.subtotal))
		data.total_price = parseFloat((sum).toFixed(10))
	})

	// 5、改变数量
	// 减数量
	function sub() {
		data.order[0].buy_amount--
		data.order[0].subtotal = parseFloat((data.order[0].buy_amount * data.order[0].goods_price).toFixed(10))
		data.total_price = data.order[0].subtotal
	}
	// 加数量
	function add() {
		data.order[0].buy_amount++
		data.order[0].subtotal = parseFloat((data.order[0].buy_amount * data.order[0].goods_price).toFixed(10))
		data.total_price = data.order[0].subtotal
	}

	// 6、提交订单
	// 点击提交
	async function submit() {
		if (data.address.length === 0) {
			new FeedBack('请选择收货地址', 'error').toast()
			return false
		}
		uni.showLoading({title: '正在下单',mask: true})
		
		// 当前时间:年月日，时分秒(下单时间)
		let order_time = moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
		// 当前时间：年月日(用于商家查询)
		let query_time = moment().utcOffset(8).format('YYYY-MM-DD')

		// 对每个商品生成随机订单编号
		data.order.forEach(item => {
			return item.order_number = orderNo()
		})

		let merchant_no = merchantNo()
		try {
			// 提交订单到数据库
			let res = await new Pay().submit(data.order, data.address, order_time, query_time, merchant_no)
			// console.log("res",res);
			
			data.merchant_no = merchant_no
			
			// 弹出支付弹窗
			uni.hideLoading()
			data.show = true
		} catch (err) {
			// 支付发生错误
			new FeedBack('支付发生错误', 'error').toast()
			// 删除数据库的订单数据
			await db.collection('order_data').where({ merchant_no }).remove()
		}
	}

	// 确认支付
	async function confirmPay() {
		console.log("result.data",data.order);
		data.loading = true
		// 1.支付成功更改订单字段为成功，跳转订单页面
		await new Pay().changeStatus('success', data.merchant_no)
		
		// 2.支付成功：库存自减，售出自增
		await new Pay().setStock(data.order)
		
		// 3.如果购物车的下单商品数据要删除
		if (data.type == 'cart') {
			let cart = await new Pay().deleteCart(data.order)
		}
		data.loading = false
		data.show = false
		// 跳转订单界面
		uni.redirectTo({ url: '/pages/order/order' })
	}

	// 取消支付
	async function cancelPay() {
		// 取消支付，删除购物车图片并跳转页面
		if (data.type == 'cart') {
			let cart = await new Pay().deleteCart(data.order)
		}
		data.show = false
		// 跳转订单界面
		uni.redirectTo({ url: '/pages/order/order' })
	}

	onBeforeUnmount(() => { 
		data.show = false 
	})
</script>

<style>
	page {
		background-color: #f6f6f6;
	}

	/* 收货地址部分 */
	.pay-address {
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.pay-address-left image {
		display: block;
		width: 40rpx;
		height: 40rpx;
	}

	.pay-address-right image {
		display: block;
		width: 30rpx;
		height: 30rpx;
	}

	.pay-address-name {
		flex: 1;
		padding: 0 20rpx;
	}

	.pay-address-name view {
		display: flex;
		align-items: center;
	}

	.pay-address-name view text:nth-child(1) {
		padding-right: 10rpx;
		font-weight: bold;
	}

	.pay-address-name view text:nth-child(2) {
		color: #8b8b8d;
	}

	/*  商品详情部分  */
	.pay-goods {
		background-color: #FFFFFF;
		display: flex;
		padding: 20rpx 20rpx 40rpx 20rpx;
	}
	


	.pay-goods text {
		display: block;
	}

	.pay-goods image {
		display: block;
		width: 200rpx;
		height: 200rpx;
		margin-right: 20rpx;
		border-radius: 6rpx;
	}

	.pay-goods>view:nth-child(2){
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	
	.pay-goods-title {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box !important;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.pay-goods-specs {
		background-color: #fafafa;
		padding: 10rpx;
		font-size: 28rpx;
		color: #a4a4a4;
	}

	.pay-goods-price {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-weight: bold;
	}

	.pay-goods-price image {
		width: 50rpx;
		height: 50rpx;
		display: block;
		margin: 0 !important;
	}

	.pay-goods-price view {
		display: flex;
		/* border: 1px solid red; */
		align-items: center;
	}

	.pay-goods-price view text {
		padding: 0 40rpx;
	}

	/* 底部提交订单 */
	.commit-order {
		background-color: #FFFFFF;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 20rpx 48rpx 20rpx;
	}

	.commit-order view:nth-child(1) {
		color: #fc324a;
		font-size: 35rpx;
		font-weight: bold;
	}

	.commit-order view:nth-child(2) {
		background-color: #ea445a;
		color: #FFFFFF;
		font-size: 35rpx;
		padding: 15rpx 35rpx;
		border-radius: 10rpx;
	}


</style>
